<template>
  <div class="app-container fix-padding-bottom">
    <div class="last-week-hour">
      <el-row>
        <el-col :span="4">
          <div class="sidebar-t">
            统计报表
          </div>
          <Sidebar class="sidebar-container" />
        </el-col>
        <el-col
          :span="20"
          class="r-cont"
        >
          <div class="m-title">
            <i
              class="el-icon-arrow-left back-report-view"
              @click="backReportView"
            />
            周案件处理时效环比统计表
          </div>
          <div class="r-top">
            <span class="l">
              图形详情
            </span>
            <span class="r">
              <em>组织：{{ org||'---' }}</em>
              <em>报表日期：{{ genDate||'---' }}</em>
              <em>统计范围：<el-select
                v-model="statRangeVmodel"
                class="filter-item"
                placeholder="请选择"
                @change="switchStatRange"
              >
                <el-option
                  v-for="(item, index) in legendOptions"
                  :key="index"
                  :label="item"
                  :value="index"
                />
              </el-select>
              </em>
              <em>周期：{{ period||'---' }}</em>
            </span>
          </div>
          <el-row
            :class="{'chart': true, 'nodata': isNoData}"
            :gutter="0"
          >
            <el-col :span="24">
              <div :class="{'area': true, 'major': isMajor0}">
                <!-- <i>有效次数</i> -->
                <ColumnChart
                  :chart-data="barData"
                  class="col-hour"
                  width="950px"
                  :height="dynamicHeight"
                />
              </div>
            </el-col>
          </el-row>
          <div class="title">
            表格详情
            <el-button
              v-waves
              class="filter-item download"
              type="primary"
              :loading="downloadLoading"
              @click="downloadExcel"
            >
              下载报表
            </el-button>
          </div>
          <el-table
            ref="singleTable"
            v-loading.body="listLoading"
            class="table-detail"
            stripe
            center
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            :newpoly="isWin32"
            height="300"
            :data="tableData"
            @current-change="handleCurrentChange"
          >
            <el-table-column
              width="150"
              label="  "
            >
              <template slot-scope="scope">
                {{ scope.row.statisticDate || '---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              label="有效工作时间"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.totalTimeThisWeek==='number'?scope.row.totalTimeThisWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              label="每小时处理案件数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.casesThisWeek==='number'?scope.row.casesThisWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="180"
              label="上周每小时处理案件数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.casesLastWeek==='number'?scope.row.casesLastWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="165"
              label="每小时有效联络数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.validConnectionsThisWeek==='number'?scope.row.validConnectionsThisWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="180"
              label="上周每小时有效联络数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.validConnectionsLastWeek==='number'?scope.row.validConnectionsLastWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="185"
              label="每小时有效联络客户数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.validConnectedCustomersThisWeek==='number'?scope.row.validConnectedCustomersThisWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="190"
              label="上周每小时有效联络客户数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.validConnectedCustomersLastWeek==='number'?scope.row.validConnectedCustomersLastWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="177"
              label="每小时PTP数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.ptpThisWeek==='number'?scope.row.ptpThisWeek:'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="180"
              label="上周每小时PTP数"
            >
              <template slot-scope="scope">
                {{ typeof scope.row.ptpLastWeek==='number'?scope.row.ptpLastWeek:'---' }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script type="text/javascript">

import { Sidebar } from '@/views/layout/components'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import { route_origins } from '@/api/routes'
import { reportViewPtpLastWeekHour, reportLastWeekExport } from '@/api/statReport'
import ColumnChart from './components/ColumnChart'
import { getExcelHeaderArray } from '@/vendor/ReadExcel'

const Export2Excel = import('@/vendor/Export2Excel')
const mockLen = 7

export default {
  name: 'LastWeekHour',
  directives: {
    waves
  },
  components: {
    Sidebar,
    ColumnChart
  },
  filters: {
    filterYMD(date) {
      return date ? parseTime(date, '{y}-{m}-{d}') : ''
    },
    filterYMDHMS(date) {
      return date ? parseTime(date) : ''
    }
  },
  data() {
    // const mockUnitArray = Array.from({ length: mockLen }, (v, i) => `催收员${i}`)
    return {
      org: '',
      genDate: '',
      period: '周',
      isNoData: false,
      isSum0: false,
      isMajor0: false,
      barData: {
        unitNames: [],
        totalTime: [],
        cases: [],
        casesLastWeek: [],
        validConnections: [],
        validConnectedCustomers: [],
        ptp: []
      },
      /* barData: {
				unitNames: mockUnitArray,
				cases: mockHourArray(),
				validConnections: mockHourArray(),
				validConnectedCustomers: mockHourArray(),
				ptp: mockHourArray()
			}, */
      lengendArr: [],
      reportId: localStorage.skyTrace && JSON.parse(localStorage.skyTrace).homeReportId || '',
      listLoading: false,
      tableData: [],
      isDownload: false,
      totalRow: '',
      currentRow: '',
      commonCaseTotalStream: '',
      // importantCaseTotalStream: '',
      // lineCaseTotalStream: '',
      downloadLoading: false,
      filename: '案件覆盖率情况统计表',
      autoWidth: true,
      isWin32: false,
      roleModel: '',
      // dynamicHeight: `${mockLen * 50}px`
      legendOptions: ['每小时处理案件数', '每小时有效联络数', '每小时有效联络客户数', '每小时PTP数'],
      legendArray: ['有效工作时间', '每小时处理案件数', '上周每小时处理案件数', '每小时有效联络数', '上周每小时有效联络数', '每小时有效联络客户数', '上周每小时有效联络客户数', '每小时PTP数', '上周每小时PTP数'],
      legendSelectedObject: {
        '有效工作时间': true,
        '每小时处理案件数': true,
        '上周每小时处理案件数': true,
        '每小时有效联络数': false,
        '上周每小时有效联络数': false,
        '每小时有效联络客户数': false,
        '上周每小时有效联络客户数': false,
        '每小时PTP数': false,
        '上周每小时PTP数': false
      },
      currentStatRange: '',
      statRangeVmodel: 0,
      dynamicHeight: `520px`
    }
  },
  computed: {
  },
  mounted() {
    console.log(arguments)
    this.getReportViewPtpLastWeekHour()
    this.isWin32 = window.navigator.platform.toLowerCase() === 'win32'
    this.roleModel = ['操作员', '小组', '部门'][localStorage.skyTrace && JSON.parse(localStorage.skyTrace).scope || 0]
    /* for (const ev in this.legendArray) {
			this.legendSelectedObject[this.legendArray[ev]] = Math.random() > 0.5
		} */
  },
  methods: {
    backReportView() {
      this.$router.push({
        path: '/statReport/reportView'
      })
    },
    mockHourArray(mode) {
      return Array.from({ length: mockLen }, n => (((Math.random() * 200) | 0) % (mode || 200)))
    },
    getReportViewPtpLastWeekHour() {
      console.log('this.reportId:', this)
      reportViewPtpLastWeekHour({
        // statRange: this.currentStatRange,
        reportId: this.reportId
      }).then(response => {
        console.log('getReportViewPtpLastWeekHour:', response, arguments)
        if (!response) return
        this.tableData = response
        this.currentRow = this.totalRow = response[response.length - 1]
        this.org = this.totalRow.aggrName || '---'
        this.genDate = this.totalRow.statisticDate || '---'
        this.setCurrentChart(this.totalRow)
        this.barData = {
          dataName: 'last-week-hour',
          legend: {
            top: -5,
            left: 150,
            width: '80%',
            textStyle: {
              fontSize: 11,
              lineHeight: 20
            },
            data: this.legendArray,
            selectedMode: false,
            selected: this.legendSelectedObject
          },
          series: [{
            name: '有效工作时间',
            type: 'bar',
            barMaxWidth: 50,
            smooth: false,
            yAxisIndex: 1,
            // data: this.mockHourArray(168)
            data: response.map(m => m.totalTimeThisWeek)
          }, {
            name: '每小时处理案件数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.casesThisWeek)
          }, {
            name: '上周每小时处理案件数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.casesLastWeek)
          }, {
            name: '每小时有效联络数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.validConnectionsThisWeek)
          }, {
            name: '上周每小时有效联络数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.validConnectionsLastWeek)
          }, {
            name: '每小时有效联络客户数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.validConnectedCustomersThisWeek)
          }, {
            name: '上周每小时有效联络客户数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.validConnectedCustomersLastWeek)
          }, {
            name: '每小时PTP数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.ptpThisWeek)
          }, {
            name: '上周每小时PTP数',
            type: 'line',
            barMaxWidth: 50,
            smooth: false,
            data: response.map(m => m.ptpLastWeek)
          }],
          unitNames: response.map(m => m.statisticDate),
          // totalTime: response.map(m => m.totalTime),
          // cases: response.map(m => m.cases),
          totalTimeThisWeek: response.map(m => m.totalTimeThisWeek),
          casesThisWeek: response.map(m => m.casesThisWeek),
          casesLastWeek: response.map(m => m.casesLastWeek),
          validConnectionsThisWeek: response.map(m => m.validConnectionsThisWeek),
          validConnectionsLastWeek: response.map(m => m.validConnectionsLastWeek),
          validConnectedCustomersThisWeek: response.map(m => m.validConnectedCustomersThisWeek),
          validConnectedCustomersLastWeek: response.map(m => m.validConnectedCustomersLastWeek),
          ptpThisWeek: response.map(m => m.ptpThisWeek),
          ptpLastWeek: response.map(m => m.ptpLastWeek)
          // totalTime: this.mockHourArray(168),
          // cases: this.mockHourArray(),
          // casesLastWeek: this.mockHourArray(),
          // validConnections: this.mockHourArray(),
          // validConnectedCustomers: this.mockHourArray(),
          // ptp: this.mockHourArray()
        }
        // this.dynamicHeight = `${mockLen * 50}px`
      }).catch(err => {
        this.$message({
          message: err && err.resultMsg || '获取平均处理时效统计表失败！',
          type: 'error'
        })
      })
    },
    switchStatRange(val) {
      console.log('switchcurrentStatRange:', val)
      this.currentStatRange = val === '' ? val : val + 1
      console.log('this.currentStatRange:', this.currentStatRange)
      // this.getReportViewPtpLastWeekHour()
      Object.keys(this.legendSelectedObject).forEach((m) => {
        this.legendSelectedObject[m] = !this.currentStatRange
      })
      if (!this.currentStatRange) return
      this.legendSelectedObject[this.legendArray[0]] = true
      this.legendSelectedObject[this.legendArray[this.currentStatRange * 2 - 1]] = this.legendSelectedObject[this.legendArray[this.currentStatRange * 2]] = true
    },
    setCurrentChart(currentRow) {
      console.log('currentRow:', currentRow)
      if (currentRow.assignCount === 0) {
        this.isNoData = true
        return
      }
      this.isNoData = false
      this.reportId = currentRow.reportBaseId
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    downloadExcel(arg) {
      this.isDownload = true
      console.log('downloadExcel-arg:', arg, this.totalRow)
      this.handleCurrentChange(this.totalRow)
      // this.chartSnapShot()
      // this.setCurrent(this.totalRow)
    },
    chartSnapShot() {
      console.log('// chartSnapShot .... :')
      reportLastWeekExport({
        reportId: this.reportId || JSON.parse(localStorage.skyTrace).homeReportId,
        image: this.commonCaseTotalStream
        // monthReturnedCountRateChartImage: this.importantCaseTotalStream,
        // dayDataListChartImage: this.lineCaseTotalStream
      }).then(response => {
        console.log('then --- reportLastWeekExport:', response)
        // 处理文件流的情况
        if (!response.resultCode) {
          this.getExcelStream(response)
          return
        }
        location.href = `${route_origins}${response.uri.slice(1, response.uri.length)}`
      }).catch(err => {
        this.$message({
          message: err && err.resultMsg || '下载统计数据失败！',
          type: 'error'
        })
      })
      // open(`/report/cover/export?reportId=${this.reportId}`)
      this.handleCurrentChange(this.currentRow)
    },
    getExcelStream(raw) {
      getExcelHeaderArray(raw, data => {
        console.log('raw-data:', data)
        const _file = new FileReader(data)
        const _blob = new Blob([_file])
        _blob.createObjectURL(this.filename + parseTime(Date.now(), '{y}{m}{d}{h}{i}') + '.xlsx')
      })
    },
    JsonToExcel() {
      console.log('export_json_to_excel:')
      this.downloadLoading = true
      Export2Excel.then(excel => {
        this.roleModel = ['操作员', '小组', '部门'][localStorage.skyTrace && JSON.parse(localStorage.skyTrace).scope || 0]
        console.log('this.roleModel:', this.roleModel)
        const tHeader = [this.roleModel, '组织', '分配案件数量', '案件触达率占比', '未触达率件数', '案件触达1次数量']
        const filterVal = ['unitName', 'orgName', 'assignCount', 'coverRate', 'count0', 'count1']
        const list = this.tableData.map((m, i) => {
          return {
            unitName: m.unitName || '---',
            orgName: m.aggrName || '---',
            assignCount: m.assignCount || '---',
            coverRate: `${m.coverRate || '---'}%`,
            count0: m.commonCase.count0 || '---',
            count1: m.commonCase.count1 || '---'
          }
        })
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename + parseTime(Date.now(), '{y}{m}{d}{h}{i}'),
          autoWidth: this.autoWidth
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleCurrentChange(curRow) {
      console.log('handleCurrentChange:', curRow)
      this.org = curRow.aggrName || '---'
      this.genDate = curRow.statisticDate || '---'
      if (!this.isDownload) {
        this.currentRow = curRow
      } else {
        const _canvas = document.querySelectorAll('canvas')
        this.commonCaseTotalStream = _canvas[0]
        // this.importantCaseTotalStream = _canvas[1]
        // this.lineCaseTotalStream = _canvas[2]
        setTimeout(img => {
          this.commonCaseTotalStream = this.commonCaseTotalStream.toDataURL()
          // this.importantCaseTotalStream = this.importantCaseTotalStream.toDataURL()
          // this.lineCaseTotalStream = this.lineCaseTotalStream.toDataURL()
          this.chartSnapShot()
        }, 1000)
      }
      this.isDownload = false
      this.setCurrentChart(curRow)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.last-week-hour{
	.sidebar-t{
		background: #01011B;
		color: white;
		font-size: 16px;
		font-weight: bolder;
		text-align: center;
		padding: 21px 0;
	}
	.r-cont{
		position: relative;
		.m-title{
			color: #4c4c4c;
			font-size: 20px;
			font-weight: bolder;
			text-align: center;
			margin-bottom: 18px;
			.back-report-view{
				background: black;
			    color: white;
			    font-size: 14px;
			    font-weight: bold;
			    padding: 3px 2px 2px 2px;
			    float: left;
			    cursor: pointer;
			}
		}
		padding: 0 10px;
		.r-top{
			.l{
				font-size: 18px;
				color: #5B5D5F;
			}
			.r{
				float: right;
				font-size: 14px;
				color: #5B5D5F;
				em{
					font-style: normal;
					margin-left: 16px;
				}
			}
			.filter-item{
		        width: 190px;
		        margin: -6px 0 0 0px;
		        .el-input__inner{
		            height: 30px !important;
		        }
		    }
		}
		.title{
			font-size: 18px;
			color: #5B5D5F;
			margin: 30px 0 0 0;
			.download{
				float: right;
				border:none;
				background: #D8D8D8;
				border-radius: 4px;
				font-family: 'MicrosoftYaHeiUI';
				font-size: 14px;
				color: #5B5D5F;
				letter-spacing: 0.75px;
				margin: -12px 0 12px 0;
			    padding-left: 10px;
			    padding-right: 11px;
			}
		}
		.chart{
			@keyframes nodata_anmi {
			    0%   { opacity: 0; }
			    // 80%   { opacity: 0; }
			    100%   { opacity: .5; }
			}
			margin: 9px 0 0px 0;
			&.nodata{
				.area{
					position: relative;
					&:after{
						content: '';
						position: absolute;
						left: -10px;
						right: 0;
						top: 0;
						bottom: 0;
						background-image: url(../../assets/stat_report/report_nodata.gif);
				        background-size: 200px 200px;
				        background-repeat: no-repeat;
				        background-position: center center;
						opacity: .5;
						transition: ease .5s opacity;
	                    animation: nodata_anmi .5s linear 1;
					}
				}
			}
			.el-col{
				.area{
					position: relative;
					&.sum, &.major{
						&:after{
							content: '';
							position: absolute;
							left: -10px;
							right: 0;
							top: 0;
							bottom: 0;
							background-image: url(../../assets/stat_report/report_nodata.gif);
					        background-size: 200px 200px;
					        background-repeat: no-repeat;
					        background-position: center center;
							opacity: .5;
							transition: ease .5s opacity;
		                    animation: nodata_anmi .5s linear 1;
						}
					}
					em{
						display: none;
						font-size: 26px;
					    font-style: normal;
					    font-weight: bolder;
					    position: absolute;
					    z-index: 10;
					    left: 46%;
					    top: 70px;
					    color: #78B7E7;
					    transform: translateX(-50%);
					    &.sec{
					    	top: 270px;
					    	color: #BF67AC;
					    }
					}
				}
				&:last-child{
					.area {
						height: 550px;
    					// width: 749px;
    					width: 100%;
						margin:0 0 0 0px;
						background: white;
						overflow-y: auto;
						i{
						    font-family: 'MicrosoftYaHeiUI';
						    font-size: 14px;
						    color: #4C4C4C;
						    font-style: normal;
						    top: 20px;
						    left: 50%;
						    position: absolute;
						    transform: translateX(-50%);
						}
						.col-hour{
							left: 24px;
							top:15px;
						}
					}
				}
			}
		}
		.unreach-percent{
			margin: 12px 0 38px 0;
			.el-col{
				.per{
					background: white;
					padding: 9px 0;
					position: relative;
					font-size: 14px;
					color: #232323;
					border-radius: 4px;
					padding-left: 30px;
					// margin: 0 10px 0 0;
					&:after{
						content: '';
						position: absolute;
						top:0;
						right: 0;
						border: 10px solid #0096E0;
						border-left: 10px solid transparent;
					    border-bottom: 10px solid transparent;
					    border-top-right-radius: 4px;
					}
				}
				&:last-child{
					.per { margin:0 0 0 10px; }
				}
			}
		}
		.table-detail{
			margin: 12px 0 0px 0;
			:after{
				content: '';
				position: absolute;
				height: 20px;
				bottom: 0;
				left: 0;
				right: 0;
			}
		}
		.bottom-mask1{
			position: absolute;
		    left: 0;
		    right: 0;
		    bottom: -8px;
		    height: 20px;
		    background: #f0f3f5;
		}
	}
}
</style>
